<template>


  <div class="header-wrapper">
    <div class="header-left">
      <div class="open-icon" >
        <i class="el-icon-s-fold" ></i>
      </div>

      <!--面包屑导航栏-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <!--<el-breadcrumb-item :to="{ path: '/home' }"><i class="el-icon-s-home" ></i> 首页</el-breadcrumb-item>-->
        <el-breadcrumb-item ><i class="el-icon-s-home" ></i> 首页</el-breadcrumb-item>

        <!--遍历导航-->
        <el-breadcrumb-item v-for="(item, index) in this.$store.state.navigationList" :key="index">{{item}}</el-breadcrumb-item>

      </el-breadcrumb>

    </div>
    <div class="header-right">

      <span class="el-dropdown-line">
        <!--头像-->
        <el-avatar size="medium" :src="headerInfo.ico" ></el-avatar>
      </span>
      &nbsp;
      <span class="header-user">{{headerInfo.username}}</span>

      <!--铃铛提示框-->
      <el-dropdown @command="handleTips" >
        <el-badge :value="badgeTip.badgeNum" :hidden="badgeTip.showBadge" :max="badgeTip.max">
          <i class="el-icon-bell" style="font-size: 15px"></i>
        </el-badge>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="birthday">
            生日提醒<el-badge class="mark" :value="birthday.num" :max="badgeTip.max" />
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>

      <el-dropdown @command="handleCommand" style="margin-left:10px;cursor: pointer">
        <i class="el-icon-setting" style="margin-right: 20px"></i>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="personalCenter">个人中心</el-dropdown-item>
          <el-dropdown-item command="updatePassword">修改密码</el-dropdown-item>
          <el-dropdown-item command="loginOut">退出</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>


      <UpdatePassword ref="updatePasswordRef"></UpdatePassword>
      <UserDetailed ref="userMainDetailedRef"></UserDetailed>

    </div>
  </div>

</template>

<script>

  import http from '@/utils/http';
  import UpdatePassword from './UpdatePassword'
  import UserDetailed from '@/components/member/UserDetailed.vue'

  export default {
    name: "Header",
    // 注册组件
    components: {
      UpdatePassword,
      UserDetailed,
    },
    data(){
      return {
        // 当前登陆人信息
        headerInfo: {
          ico: require('@/assets/images/avatar/avatar12.png'),
          username: 'admin'
        },
        // 提示信息，小红点提示信息
        badgeTip: {
          // 是否显示小红点,true 不显示
          showBadge: true,
          // 小红点提示总数,总的消息数量
          badgeNum: 0,
          // 最多显示的数量
          max: 99,
        },
        // 生日相关信息
        birthday: {
          // 生日消息的总数
          num: 0,
          // 生日数据
          birthdayVo: null,
        },
        // 定时器
        timer: null,
      }
    },
    methods: {
      /**
       * 下拉菜单事件管理
       */
      handleCommand(command) {
        if (command === 'loginOut') {
          this.logout();
        } else if (command === 'updatePassword') {
          // 调用子组件的弹出框
          this.$refs.updatePasswordRef.updatePasswordShow = true
        } else if (command === 'personalCenter'){
          // 个人中心
          http.post("/user/getMemberFamilyById", {
          }).then(response => {
            let res = response.data;
            if (res.status === 'error'){
              if (res.code !== 401){
                this.$message.error(res.msg);
              }
              return
            }
            this.$refs.userMainDetailedRef.openUserDetailed(res.data)

          }).catch(error => {
            this.$message.error(error.message);
          })
        }
      },
      /**
       * 下拉生日的提示
       * @param command 事件
       */
      handleTips(command){
        if (command === 'birthday'){
          // 如果是生日的消息跳转到生日消息列表
          this.$router.push({path: "/toBirthdayList"})
        }
      },
      /**
       * 登出
       */
      logout(){
        http.post("/user/logout").then(response => {
          let res = response.data;
          if (res.status === 'error'){
            // 401是token过期跳转的
            if (res.code !== 401){
              this.$message.error(res.msg);
            }
            return
          }
          this.$router.push({path: "/"})

        }).catch(error => {
          this.$message.error(error.message);
        })
      },
      /**
       * 获取生日人员
       */
      getBirthdayList(){
        http.get("/birthday/getBirthdayList", {
        }).then(response => {
          let res = response.data;
          if (res.status === 'error'){
            // 401是token过期跳转的
            if (res.code !== 401){
              this.$message.error(res.msg);
            }
            return
          }
          this.birthday.birthdayVo = res.data
          if (this.birthday.birthdayVo != null){
            // 展示小红点
            if (this.birthday.birthdayVo.soonList != null && this.birthday.birthdayVo.soonList.length > 0){
              // 生日的小红点数
              this.birthday.num = this.birthday.birthdayVo.soonList.length
              // 总的小红点数，只要总的数量变了，非0就会显示出小红点
              this.badgeTip.badgeNum = this.birthday.birthdayVo.soonList.length
            }
          }

        }).catch(error => {
          this.$message.error(error.message);
        })
      },
      /**
       * 获取小时级别的任务-固定任务到秒级别的
       */
      getHourTask(){
        http.get("/plan/getHourTask", {}).then(response => {
          let res = response.data;
          if (res.status === 'error'){
            // 401是token过期跳转的
            if (res.code !== 401){
              this.$message.error(res.msg);
            }
            return
          }
          let data = res.data
          if (data){
            // 将任务推送展示
            for (let obj of data){
              this.popNotice("Hi,有新提醒", obj.name + "【" + obj.details + "】")
            }
          }

        }).catch(error => {
          this.$message.error(error.message);
        })
      },
      /**
       * 刷新家庭作业
       * 单纯的刷新，不做获取.这里等于当定时任务用
       */
      refreshHomework(){
        http.get("/homework/refreshHomework", {}).then(response => {
          let res = response.data;
          if (res.status === 'error'){
            // 401是token过期跳转的
            if (res.code !== 401){
              this.$message.error(res.msg);
            }
            return
          }
          let data = res.data
          if (data){
            // 不会进行任务操作，就是一个单纯的定时任务
          }

        }).catch(error => {
          this.$message.error(error.message);
        })
      },
      /**
       * 判断是否支持浏览器通知
       * @return true 支持通知
       */
      judgmentSupportNotification(){
        if (window.Notification) {
          // 浏览器通知--window.Notification
          if (Notification.permission === "granted") {
            console.log("允许通知")
            return true

          }else if( Notification.permission !== "denied"){
            console.log("需要通知权限,请点击开放该权限，否则无法正常使用")
            this.$message.error("请点击开启通知权限，否则无法正常使用，点击地址栏的通知图标开启");

            // 请求权限
            Notification.requestPermission((permission)=> {
              //console.log(permission) // granted, denied, 或default
              // 其中granted表示用户允许通知，denied表示用户嫌弃你，default表示用户目前还没有管你。
              if ("granted" === permission){
                this.popNotice("Hi,有新提醒", "已开启计划推送提醒")
                return true
              } else if (Notification.permission === "denied") {
                this.$message.error("拒绝通知将导致任务与家庭作业模块不正常");
                return false
              } else {
                return false;
              }
            });
          }
        } else {
          console.error('浏览器不支持Notification');
          this.$message.error("浏览器不支持Notification");
          return false
        }
      },
      /**
       * 打开一个通知
       * @param title 消息标题，是必须参数
       * @param content 提示主体内容
       */
      popNotice(title, content) {
        let that = this;
        if (Notification.permission === "granted") {
          let notification = new Notification(title, {
            body: content,
            icon: require('@/assets/images/avatar/avatar9.jpg')
          });

          notification.onclick = function(e) {
            that.$nextTick(() => {
              setTimeout(()=>{
                //具体操作
              },500);
            });
            //可直接打开通知notification相关联的tab窗
            window.focus();
            notification.close();
          };
        }
      },
    },
    /**
     * 渲染页面后执行的函数
     */
    mounted(){
      // 读取缓存，填充信息
      let localStorage = window.localStorage;
      let memberFamily = JSON.parse(localStorage.memberFamily);
      if (memberFamily){
        this.headerInfo.username = memberFamily.userName
        if (memberFamily.icoPath){
          this.headerInfo.ico = memberFamily.icoPath
        } else {
          // 不存在则使用默认的
          this.headerInfo.ico = require('@/assets/images/avatar/avatar12.png')
        }
      }

      this.getBirthdayList()

      if (this.judgmentSupportNotification()){
        // 开始调用定时器,定时获取任务
        this.timer = setInterval(() => {
          // 执行定时任务
          this.getHourTask()
          this.refreshHomework()
        // },180000)
        },60000)
      }
    },
    /**
     * 销毁组件的时候
     */
    destroyed(){
      // 清空定时器
      clearInterval(this.timer)
      console.log("任务推送定时器销毁")
    },
    // 监听器
    watch: {
      // 监听总的数量
      'badgeTip.badgeNum'() {
        // 根据消息总数显示是否带提示框
        if (this.badgeTip.badgeNum === 0){
          this.badgeTip.showBadge = true
        } else {
          this.badgeTip.showBadge = false
        }
      }
    }
  }
</script>

<style scoped>

  .header-wrapper {
    display: flex;
    justify-content: space-between;
    align-content: center;
    /*padding: 0 125px;*/
    padding-left: 155px;
    height: 60px;
  }
  .header-wrapper .header-left {
    display: flex;
    align-items: center;
  }
  .header-wrapper .header-left .open-icon {
    font-size: 20px;
    margin-right: 15px;
    cursor: pointer;
  }
  .header-wrapper .header-right {
    display: flex;
    align-items: center;
  }
  .header-wrapper .header-right .header-user {
    margin-right: 5px;
    /*用户姓名和颜色*/
    font-size: 12px;
    color: #606266;
  }

  .el-dropdown-link {
    cursor: pointer;
    color: #409eff;
  }
  .el-dropdown-link img {
    width: 40px;
    height: 40px;
    border-radius: 5px;
  }

  .el-icon-arrow-down {
    font-size: 12px;
  }

  .demostration {
    display: block;
    color: #8492a6;
    font-size: 14px;
    margin-bottom: 20px;
  }

</style>
